//this is the main function
function checkForm() {
    //collecting user inputs
    firstname = document.getElementById("firstname").value;
    surname = document.getElementById("surname").value;
    age = document.getElementById("age").value;
    //calls another function IsNumeric
    ageNumeric = IsNumeric(age);
    phone = document.getElementById("phone").value;
    //calls another function IsNumeric
    phoneNumeric = IsNumeric(phone);
    email = document.getElementById("email").value;
    //calls another function checkEmail
    emailResult = checkEmail(email);
    customer = document.getElementById("customer").value;
    Duration = document.getElementById("Duration").value;


    //checking for empty inputs and displaying error
    if (firstname == "") {
        hideAllErrors();
        document.getElementById("firstnameError").style.display = "inline";
        document.getElementById("firstname").select();
        document.getElementById("firstname").focus();
        return false;
    } else if (surname == "") {
        hideAllErrors();
        document.getElementById("surnameError").style.display = "inline";
        document.getElementById("surname").select();
        document.getElementById("surname").focus();
        return false;
    } else if (age == "") {
        hideAllErrors();
        document.getElementById("ageError").style.display = "inline";
        document.getElementById("age").select();
        document.getElementById("age").focus();
        return false;
    } else if (ageNumeric == false) {
        hideAllErrors();
        document.getElementById("ageError").style.display = "inline";
        document.getElementById("age").select();
        document.getElementById("age").focus();
        return false;
    }

    // checks if age is between 16 and 90
    else if (age < 16 || age > 90) {
        hideAllErrors();
        document.getElementById("ageError").style.display = "inline";
        document.getElementById("age").select();
        document.getElementById("age").focus();
        return false;
    } else if (phone == "") {
        hideAllErrors();
        document.getElementById("phoneError").style.display = "inline";
        document.getElementById("phone").select();
        document.getElementById("phone").focus();
        return false;
    } else if (phoneNumeric == false) {
        hideAllErrors();
        document.getElementById("phoneError").style.display = "inline";
        document.getElementById("phone").select();
        document.getElementById("phone").focus();
        return false;
    } else if (email == "") {
        hideAllErrors();
        document.getElementById("emailError").style.display = "inline";
        document.getElementById("email").select();
        document.getElementById("email").focus();
        return false;
    } else if (emailResult == false) {
        hideAllErrors();
        document.getElementById("emailError").style.display = "inline";
        document.getElementById("email").select();
        document.getElementById("email").focus();
        return false;

    } else if (customer == "choose yours") {
        hideAllErrors();
        document.getElementById("customerError").style.display = "inline";
        document.getElementById("customer").focus()
        return false;
    } else if (Duration == "choose yours") {
        hideAllErrors();
        document.getElementById("DurationError").style.display = "inline";
        document.getElementById("Duration").focus();
        return false;
    }


// this is to tell user all validation is now complete
    alert("First Name:" + firstname + "\n Surname:" + surname + "\n Age:" + age + "\n Phone Number:" + phone + "\n Email:" + email + "\n Customer Type:" + customer + "\n Duration" + Duration);

    return true;

}


//checks via reg ex if age and phone numbers are numbers
function IsNumeric(numstr) {
    mystring = numstr;
    if (mystring.match(/^\d+$/)) {

        return true;
    } else {
        return false;
    }
}

//checks if email is in proper email format
function checkEmail(inputvalue) {
    var pattern = /^([a-zA-Z0-9_.-])+@([a-zA-Z0-9_.-])+\.([a-zA-Z])+([a-zA-Z])+/;
    if (pattern.test(inputvalue)) {
        return true;
    } else {
        return false;
    }


}

// hide error upon successful validation
function hideAllErrors() {
    document.getElementById("firstnameError").style.display = "none";
    document.getElementById("surnameError").style.display = "none";
    document.getElementById("ageError").style.display = "none";
    document.getElementById("phoneError").style.display = "none";
    document.getElementById("emailError").style.display = "none";
    document.getElementById("customerError").style.display = "none";
    document.getElementById("DurationError").style.display = "none";


}


// adjust input columns for family member
function changeFunc() {
    var selectBox = document.getElementById('customer');
    var selectedValue = selectBox.options[selectBox.selectedIndex].value;

    if (selectedValue == 'Family') {
        document.getElementById("div_member_number").style.display = "block";
        var memberNumber = document.getElementById("family_member_number").value;
        createAgeDiv(memberNumber, "additional_member_info")
    }
    if (selectedValue == 'Individual') {
        document.getElementById("div_member_number").style.display = "none";
    }
}

// sub function to insert div
function createAgeDiv(memberNumber, idToInsert) {
    var htmlElements = "";
    for (var i = 1; i <= memberNumber; i++) {
        htmlElements += '<div class="additional_member_form_row">\n' +
            '                    <span class="label">member ' + i + ' age:</span>\n' +
            '                    <input class="member_age" type="number"\n' +
            '                           min="16" step="1" max="90" pattern="\\d+" value="20"\n' +
            '                    />\n' +
            '                </div>';
    }
    var container = document.getElementById(idToInsert);
    container.innerHTML = htmlElements;

}


// the function for button to call by onclick event
function calculateFee() {
    if (checkFeeColumns()) {
        hideAllErrors();
        // some variable for fee calculate
        var individual_fee = 50;
        var familyDiscount, referDiscount = 0.0;
        var membersAgeDiscount = [0.0];

        //
        var selectBox = document.getElementById('customer');
        var selectedValue = selectBox.options[selectBox.selectedIndex].value;
        if (selectedValue == 'Family')
            if (selectedValue == 'Family') {
                // if Family memmber existed, apply 80% dicount to(50->40)
                familyDiscount = 0.2;
                membersAgeDiscount = getMemberAgeDiscount("member_age", membersAgeDiscount)
            }
        if (selectedValue == 'Individual') {
            // if Individual, no familyDiscount
            familyDiscount = 0.0;
            var selector = 'input[name=age]'
            var age = document.querySelector(selector).value;
            var ageDiscount = 0.0
            if (age >= 16 && age <= 19)
                ageDiscount = 0.1
            membersAgeDiscount = [ageDiscount]
        }
        referDiscount = getReferDiscount(membersAgeDiscount.length, "refer")
        var total_fee = calculateTotalFee(individual_fee, membersAgeDiscount, familyDiscount, referDiscount);
        document.getElementById("fee_value").textContent = "$" + total_fee;
    }
}

// get the total fee calculated, applied the triple discount
function calculateTotalFee(individual_fee, membersAgeDiscount, familyDiscount, referDiscount) {
    var total_fee = 0;
    for (var i = 0; i < membersAgeDiscount.length; i++) {
        total_fee += individual_fee * (1 - familyDiscount) * (1 - referDiscount) * (1 - membersAgeDiscount[i])
    }
    var selectBox = document.getElementById('Duration');
    var duration = selectBox.options[selectBox.selectedIndex].value;
    if (IsNumeric(duration)) {
        return total_fee * duration;
    } else {
        hideAllErrors();
        document.getElementById("DurationError").style.display = "inline";
        document.getElementById("Duration").focus();
        return 0;
    }

}

// get the members age discount
function getMemberAgeDiscount(member_age_class, membersAgeDiscount) {
    // get the members age input list by class name.
    var memberAgeList = document.getElementsByClassName(member_age_class);
    for (var i = 0; i < memberAgeList.length; i++) {
        var memberAge = memberAgeList[i].value;
        // if  16<=age<=19 ,get 10% discount
        if (memberAge >= 16 && memberAge <= 19) {
            membersAgeDiscount[i] = 0.1
        } else {
            membersAgeDiscount[i] = 0.0
        }
    }
    return membersAgeDiscount
}

// get the refer discount
function getReferDiscount(length, inputRadioName) {
    var referDiscount = 0.0;
    var selector = 'input[name=' + inputRadioName + ']:checked'
    var isReferred = document.querySelector(selector).value == "yes";
    // if not referred OR members number>5, no refer discount applied.else get 5% discount
    if (!isReferred || length > 5) {
        referDiscount = 0.0;
    } else {
        if (isReferred)
            referDiscount = 0.05;
    }
    return referDiscount;
}

function checkFeeColumns() {
    age = document.getElementById("age").value;
    //calls another function IsNumeric
    ageNumeric = IsNumeric(age);
    customer = document.getElementById("customer").value;
    Duration = document.getElementById("Duration").value;
    if (age === "") {
        hideAllErrors();
        document.getElementById("ageError").style.display = "inline";
        document.getElementById("age").select();
        document.getElementById("age").focus();
        return false;
    } else if (ageNumeric === false) {
        hideAllErrors();
        document.getElementById("ageError").style.display = "inline";
        document.getElementById("age").select();
        document.getElementById("age").focus();
        return false;
    }
    // checks if age is between 16 and 90
    else if (age < 16 || age > 90) {
        hideAllErrors();
        document.getElementById("ageError").style.display = "inline";
        document.getElementById("age").select();
        document.getElementById("age").focus();
        return false;
    } else if (customer === "choose yours") {
        hideAllErrors();
        document.getElementById("customerError").style.display = "inline";
        document.getElementById("customer").focus()
        return false;
    } else if (Duration === "choose yours") {
        hideAllErrors();
        document.getElementById("DurationError").style.display = "inline";
        document.getElementById("Duration").focus();
        return false;
    }

    return true;
}
